package com.ah.service;

import com.ah.common.result.R;
import com.ah.common.service.IStockService;
import com.ah.entity.TStock;
import com.ah.mapper.StockMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

@DubboService
public class StockServiceImpl implements IStockService {
    @Autowired
    private StockMapper stockMapper;

    @Override
    public R deduct(String commodityCode, int count) {
        LambdaQueryWrapper<TStock> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TStock::getCommodityCode,commodityCode);

        TStock tStock = stockMapper.selectOne(lambdaQueryWrapper);
        if(Objects.isNull(tStock)){
            return R.error("商品不存在");
        }

        if(tStock.getCount() < count){
            return R.error("商品库存不足");
        }

        //扣减库存
        tStock.setCount(tStock.getCount()-count);

        //修改数据库
        int row = stockMapper.updateById(tStock);
        if(row == 1){
            return R.success();
        }

        return R.error("服务异常");
    }
}
